package ru.yermak.bookkeeping.account;

import ru.yermak.bookkeeping.model.Account;
import ru.yermak.bookkeeping.model.AccountValue;
import ru.yermak.bookkeeping.model.Currency;
import ru.yermak.bookkeeping.common.BookkeeperState;
import ru.yermak.bookkeeping.currency.CurrencyDao;
import ru.yermak.bookkeeping.ui.DataTableModel;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.stereotype.Component;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * User: harrier
 * Date: Aug 10, 2008
 */
@Component
public class AccountTableModel extends DataTableModel<Account> {

    private final Log log = LogFactory.getLog(this.getClass());

    private List<Currency> currencies;
    private BookkeeperState bookkeeperState;
    private CurrencyDao currencyDao;
    private AccountDao accountDao;


    @Autowired
    public AccountTableModel(BookkeeperState bookkeeperState, CurrencyDao currencyDao, AccountDao accountDao) {
        this.bookkeeperState = bookkeeperState;
        this.currencyDao = currencyDao;
        this.accountDao = accountDao;
    }


    public String getColumnName(int column) {
        if (currencies == null) return null;
        if (column == 0) {
            return "Account";
        }
        return currencies.get(column - 1).getCode();
    }


    public int getColumnCount() {
        log.debug("Account column count = " + (currencies == null ? 0 : currencies.size() + 1));
        if (currencies == null) return 0;
        return currencies.size() + 1;
    }


    public Object getValueAt(int rowIndex, int columnIndex) {
        Account account = getData().get(rowIndex);
        if (columnIndex == 0) {
            return account.getName();
        }

        Set<AccountValue> accountValues = account.getAccountValues();
        Currency currency = currencies.get(columnIndex - 1);
        for (AccountValue accountValue : accountValues) {
            if (accountValue.getCurrency().equals(currency)) {
                System.out.println("accountValue = " + accountValue.getValue());
                return accountValue.getValue();
            }
        }
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void load() {
        if (bookkeeperState.isValid()) {
            setData(accountDao.getAccountsByUserId(bookkeeperState.getUserId()));
            currencies = currencyDao.findCurrencyByUserId(bookkeeperState.getUserId());
            this.fireTableDataChanged();
        }
    }

    public void clean() {
        rowCount = 0;
        data = null;
        currencies = null;
    }

}
